import { app, BrowserWindow, ipcMain } from 'electron';
import Store from "electron-store";
import { editorSettings, settingsInitData, TableInitData, textInitData } from './utils/defaultData';
import * as fs from 'fs';
import * as path from 'path';
import { Menu, dialog } from 'electron';
const store = new Store();
let mainWindow:BrowserWindow
let projectData:ProjectData
let appCache = store.get("appCache") as AppCache
// 存储所有创建的窗口
let windows: BrowserWindow[] = [];

let initProjectData = ()=>{
  projectData = {text:textInitData, table:TableInitData, settings: settingsInitData}
}
let loadProjectData = async(path:string)=>{ 
  let result = await readJsonFile(path)
  if (result.success) {
    projectData = result.data
  } else {
    initProjectData()
  }
}

let saveData = async (data:any) => { 
  // 直接使用appCache.projectPath作为完整路径
  const filePath = appCache.projectPath;
  try {
    await fs.promises.writeFile(filePath, JSON.stringify(data, null, 2));
    return { success: true, message: 'Store saved to local path successfully' + filePath };
  } catch (error) {
    const logPath = path.join(process.cwd(), 'main-process-logs.txt');
    const logMessage = `[${new Date().toISOString()}] Error: Failed to save store to local path: ${error}
`;
    fs.appendFileSync(logPath, logMessage);
    console.error('Failed to save store to local path:', error);
    if (error instanceof Error) {
      return { success: false, error: error.message };
    }
    return { success: false, error: String(error) };
  }
}
let initAppCache = ()=>{
    appCache = { projectPath:"projectData.json", editorSettings:editorSettings}
}
app.whenReady().then(async () =>{
  // 数据初始化
  if (!appCache) { 
    initAppCache();
    store.set("appCache",appCache)
    initProjectData()
  } else {
    await loadProjectData(appCache.projectPath)
  }
  
  // 创建菜单
  createMenu();
  
  mainWindow = createManagerWindow("config")
})

// 封装读取JSON文件的函数
async function readJsonFile(filePath: string) {
  try {
    // 确保文件路径存在
    if (!fs.existsSync(filePath)) {
      return { success: false, error: `File not found: ${filePath}` };
    }

    // 读取文件内容
    const data = await fs.promises.readFile(filePath, 'utf-8');

    // 解析JSON
    const jsonData = JSON.parse(data);

    return { success: true, data: jsonData };
  } catch (error) {
    const logPath = path.join(process.cwd(), 'main-process-logs.txt');
    const logMessage = `[${new Date().toISOString()}] Error: Failed to read data from file: ${error}
`;
    fs.appendFileSync(logPath, logMessage);
    console.error('Failed to read data from file:', error);
    if (error instanceof Error) {
      return { success: false, error: error.message };
    }
    return { success: false, error: String(error) };
  }
}

// 封装窗口创建通用函数
function createManagerWindow(managerType: 'app'| 'data' | 'text' | 'config' | 'template' | 'setting' | 'exportSetting') {
  let win = new BrowserWindow({
    width: 1280,
    height: 900,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });
  
  // 将窗口添加到数组
  windows.push(win);
  
  // 窗口关闭时从数组中移除
  win.on('closed', () => {
    windows = windows.filter(w => w !== win);
  });
  
  let htmlName;
    if (managerType === 'setting') {
      htmlName = `index_setting.html`;
    } else if (managerType === 'exportSetting') {
      htmlName = `index_exportSetting.html`;
    } else {
      htmlName = `index_${managerType}Manager.html`;
    }
  if (process.argv[2]) {
    let ip = process.argv[2];
    win.loadURL(`${ip}/${htmlName}`);
  } else {
    win.loadFile(htmlName);
  }
  
  win.webContents.openDevTools();
  return win;
}

// 创建菜单
function createMenu() {
  const template = [{
    label: '文件',
    submenu: [{
      label: '新建',
      click: () => {
        // 清空projectPath
        appCache.projectPath = '';
        store.set('appCache', appCache);
        // 初始化项目数据
        initProjectData();
        // 向所有窗口发送更新事件
        windows.forEach(win => {
          win.webContents.send('dataUpdated', {table: projectData.table, text: projectData.text});
        });
      }
    }, {
      label: '打开',
      click: () => {
        openDataFile();
      }
    }, {
      label: '保存',
      click: () => {
        saveDataWithCheck();
      }
    }, {
      label: '另存为',
      click: () => {
        saveAsData();
      }
    }]
  }, {
    label: '设置',
    submenu: [{
      label: '导出设置',
      click: () => {
        createManagerWindow('exportSetting');
      }
    }]
  }];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// 打开文件函数
async function openDataFile() {
  const result = await dialog.showOpenDialog({
    filters: [{
      name: 'JSON Files',
      extensions: ['json']
    }],
    properties: ['openFile']
  });

  if (!result.canceled && result.filePaths && result.filePaths.length > 0) {
    const filePath = result.filePaths[0];
    // 更新projectPath
    appCache.projectPath = filePath;
    store.set('appCache', appCache);
    // 加载文件数据
    const loadResult = await readJsonFile(filePath);
    if (loadResult.success) {
      projectData = loadResult.data;
      // 通知所有窗口数据已更新
      windows.forEach(win => {
        win.webContents.send('dataUpdated', {table: projectData.table, text: projectData.text});
      });
    } else {
      dialog.showErrorBox('错误', `无法打开文件: ${loadResult.error}`);
    }
  }
}

// 带检查的保存函数
async function saveDataWithCheck() {
  if (!appCache.projectPath) {
    await saveAsData();
  } else {
    await saveData(projectData);
    // 保存成功后通知所有窗口
    windows.forEach(win => {
      win.webContents.send('saveSuccess');
    });
  }
}

// 另存为函数
async function saveAsData() {
  const result = await dialog.showSaveDialog({
    filters: [{
      name: 'JSON Files',
      extensions: ['json']
    }],
    defaultPath: path.join(process.cwd(), 'projectData.json')
  });

  if (!result.canceled && result.filePath) {
    appCache.projectPath = result.filePath;
    store.set('appCache', appCache);
    await saveData(projectData);
    // 保存成功后通知所有窗口
    windows.forEach(win => {
      win.webContents.send('saveSuccess');
    });
  }
}

// 添加存储处理器
ipcMain.handle('saveTextStore', async (event, data) => {
  projectData.text = data;
  let result = await saveData(projectData);
  if (mainWindow != null) {
    mainWindow.webContents.send('textChanged', projectData.text);
  }
  return result;
});
interface AppCache {
  projectPath:string,
  editorSettings: any
}
interface ProjectData { 
  text:any
  table:any
  settings:any
}

ipcMain.handle('getData', async() => {
  return {table:projectData.table, text:projectData.text, editorSettings:appCache.editorSettings, settings:projectData.settings}
});

ipcMain.handle('saveTableStore', (event, data) => {
  store.set('tableStore', data);
})
ipcMain.handle('getTableStore', async() => {
  return projectData.table
})


ipcMain.handle('saveStoreToLocal', async (event, data) => {
  projectData.table = data
  return await saveData(projectData)
})
ipcMain.on('open-text-manager', () => {
  createManagerWindow('text');
});

// 打开设置窗口
ipcMain.on('open-setting-window', () => {
  createManagerWindow('setting');
});

// 打开导出设置窗口
ipcMain.on('open-export-setting-window', () => {
  createManagerWindow('exportSetting');
});

// 保存设置
ipcMain.handle('saveSettingStore', async (event, data) => {
  try {
    // 这里可以添加保存设置的逻辑
    // 例如保存到projectData或单独的设置文件
    projectData.settings = data;
    await saveData(projectData);
    return { success: true, message: '设置保存成功' };
  } catch (error) {
    return { success: false, error: String(error) ,projectData:projectData};
  }
});

// 确认对话框
ipcMain.handle('confirmDelete', async (event, message) => {
  const result = await dialog.showMessageBox({
    type: 'question',
    buttons: ['取消', '确定'],
    title: '确认',
    message: message
  });
  return result.response === 1;
});